package com.bjut.dailyserver.controller;

import com.bjut.dailyserver.dao.TBriefNewsDao;
import com.bjut.dailyserver.dao.TCollectionDao;
import com.bjut.dailyserver.entity.TBriefNews;
import com.bjut.dailyserver.entity.TCollection;
import com.bjut.dailyserver.entity.TUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/collection")
public class TCollectionController {
    @Autowired
    TCollectionDao tCollectionDao;

    @RequestMapping("findById")
    @ResponseBody
    public Object findById(Long id) {return tCollectionDao.findById(id);}

    @RequestMapping("/save")
    @ResponseBody
    public Object save(TCollection tCollection) {
        if(tCollection.getId() != null) {
            return tCollectionDao.save(tCollection);
        }

        List<TCollection>list = tCollectionDao.findByTUserAndTBriefNews(tCollection.gettUser(), tCollection.gettBriefNews());
        TCollection temp = (list==null||list.size()==0?null:list.get(0));
        if (temp == null) {
            return tCollectionDao.save(tCollection);
        } else {
            return tCollectionDao.save(temp);
        }
    }

    @RequestMapping("/findCollectionByTUserAndTBriefNews")
    @ResponseBody
    public Object findNewsByUserAndNews(TCollection tCollection) {
        return tCollectionDao.findByTUserAndTBriefNews(tCollection.gettUser(), tCollection.gettBriefNews());
    }

    @RequestMapping("/findIdByTUserAndTBriefNews")
    @ResponseBody
    public Long findIdByUserAndNews(TCollection tCollection) {
        List<TCollection>list = tCollectionDao.findByTUserAndTBriefNews(tCollection.gettUser(), tCollection.gettBriefNews());
        TCollection temp = (list==null||list.size()==0?null:list.get(0));
        if (temp != null) {
            return temp.getId();
        } else {
            return (long) -1;
        }
    }

    @RequestMapping("/deleteById")
    @ResponseBody
    public void deleteById(TCollection tCollection) {tCollectionDao.deleteById(tCollection.getId());}

    @RequestMapping("/findCollectionByUser")
    @ResponseBody
    public Object findNewsByUser(TUser tUser) {
        return tCollectionDao.findByTUser(tUser);
    }
}
